package data_treating

import (
	"errors"
	"fmt"
	"goocr/config"
	"io/ioutil"
	"os"
	"strings"
	"time"
)

// 获取日期目录下所有图片
func GetPictures() ([]string, error) {
	var s []string
	path, err := GetImgPath()
	if err != nil {
		return s, err
	}
	rd, err := ioutil.ReadDir(path)
	if err != nil {
		return s, err
	}
	for _, fi := range rd {
		if !fi.IsDir() {
			s = append(s, fmt.Sprintf("%s%s", path, fi.Name()))
		}
	}
	return s, nil
}

// 获取图片目录
func GetImgPath() (s string, err error) {
	dirName := time.Now().Add(-time.Hour * time.Duration(config.Conf.Tim)).Format(TimeFormat)
	wd, _ := os.Getwd()
	s = fmt.Sprintf("%s%s%s", wd, "/"+normalPictureDir+"/", dirName)
	has, _ := pathExists(s)
	if !has {
		return s, errors.New(fmt.Sprintf("目录%s不存在", s))
	}
	return s, nil
}

// 文件另存
func saveAs(sourceFile string) (err error) {
	wd, _ := os.Getwd()
	sourceFileArr := strings.Split(sourceFile, "/")
	destinationFile := fmt.Sprintf("%s%s%s", wd, "/"+abnormalPictureDir+"/", sourceFileArr[len(sourceFileArr)-1])
	data, err := ioutil.ReadFile(sourceFile) //read the contents of source file
	if err != nil {
		err = errors.New(fmt.Sprintf("Error reading file:%v", err))
		return
	}
	err = ioutil.WriteFile(destinationFile, data, 0644) //write the content to destination file
	if err != nil {
		err = errors.New(fmt.Sprintf("Error writing file:%v", err))
		return
	}
	return
}

// 删除文件
func RemoveFile(filePath string) (err error) {
	// 删除文件
	err = os.Remove(filePath)
	if err != nil && !os.IsNotExist(err) { // 不再报告“文件不存在”的错误
		err = errors.New(fmt.Sprintf("删除文件错误:%v", err))
	}
	return
}

// 异常图片处理
func AbnormalPicture(sourceFile string) (err error) {
	if err = saveAs(sourceFile); err != nil {
		return
	}
	if err = RemoveFile(sourceFile); err != nil {
		return
	}
	return
}
